<template>
  <el-main>
    <el-upload
      class="avatar-uploader"
      :action="domain2"
      :show-file-list="false"
      :headers="myHeaders"
      :data="QiniuData"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </el-main>
</template>

<script>
import {getToken} from "@/utils/auth";
import {getAuthToken} from "@/api/file";

export default {
  name: "upload2",
  data() {
    return {
      imageUrl: '',
      myHeaders:{ 'Authorization': 'Bearer ' + getToken() },
      RuestToken:null,
      loading: false,
      QiniuData: {
        key: "", //图片名字处理
        token: "" //七牛云token
      },
      // 七牛云的上传地址（华南区） 七牛云服务器
      domain: "https://upload-z2.qiniup.com",
      // 自己的服务器
      domain2: "http://localhost/dev-api/file/qiniu/upload",
      qiniuaddr: "\n" +
        "http://rcdx67svg.hn-bkt.clouddn.com", // 七牛云的图片外链地址
      uploadPicUrl: "", //提交到后台图片地址
      fileList: []
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      /*      const isPNG = file.type === "image/png";
            const isJPEG = file.type === "image/jpeg";
            const isJPG = file.type === "image/jpg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isPNG && !isJPEG && !isJPG) {
              this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
              return false;
            }
            if (!isLt2M) {
              this.$message.error("上传头像图片大小不能超过 2MB!");
              return false;
            }*/
      // 文件名字拼接
      this.QiniuData.key = `upload_pic_${file.name}`;
    },
    // 上传成功修   拼接图片访问路径
    uploadSuccess(response, file, fileList) {
      console.log(fileList);
      this.uploadPicUrl = this.qiniuaddr+"/"+response.key;
      // this.uploadPicUrl = this.qiniuaddr+"/"+response;
      // 视屏上传成功需要修改 为vidio 播放
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    //请求后台拿七牛云token
    getQiniuToken() {
      getAuthToken().then(rep=>{
        this.QiniuData.token = rep;
      })
    },
  },

  created() {
    this.getQiniuToken();
  }
}

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
